package edu.mercer.sse658.amazonbkp;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.google.common.base.Optional;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;


/**
 * Amazon account credentials information.<p>
 *
 * Builder API.<br>
 * Path, File amazon credentials validation and parsing. 
 */

public class AmazonCredentials 
{
	private AWSCredentials _awsCredentials = null;

	
	public AmazonCredentials( final AWSBuilder awsCredBldr ) throws 
			IOException
	{
		init( awsCredBldr.getPath() );
		
	}//constructor

	
	private AmazonCredentials init( final Path pathIn ) throws IOException 
	{
		checkArgument( pathIn
				  	   .toFile()
				  	   .exists() &
				  					 
					   pathIn
				  	   .toFile()
				  	   .canRead() &
				  					 
				  	   pathIn
				  	   .toFile()
				  	   .length() > 0,

				  "not found, inaccesible, or empty: " + pathIn.toString() );

		_awsCredentials = new PropertiesCredentials( pathIn.toFile() );
		
		checkNotNull( _awsCredentials.getAWSAccessKeyId(),
				"AWS access key null" );
		
		checkNotNull( _awsCredentials.getAWSSecretKey(),
				"AWS secret key null" );
		
		return this;
		
	}//method
		
	
	public static AWSBuilder builder()
	{
		return new AWSBuilder();
		
	}//method

	
	public AWSCredentials getAWSCredentials()
	{
		checkNotNull( _awsCredentials, 
				"not initialized, builder usage required" );
		
		return _awsCredentials;
		
	}//method
	
	
}//class
	

class AWSBuilder
{
	private Optional<Path> _awsCredentialsPath = Optional.of( 
			Paths.get("credentials.aws") );

	
	public AWSBuilder()
	{			
	}//constructor
	
	
	public AWSBuilder withPath( final Path pathIn )
	{
		_awsCredentialsPath = Optional.of( pathIn );
		
		return this;
		
	}//method


	public AWSBuilder withPath( final String pathIn )
	{
		return withPath( Paths.get( pathIn ) );
		
	}//method

	
	public Path getPath()
	{
		return _awsCredentialsPath.get();
		
	}//method
	
	
	public AWSCredentials build() throws IOException
	{
		return new AmazonCredentials(this).getAWSCredentials();
		
	}//method
	
	
}//class
